package com.blockchain.securewallet.activities;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.support.v7.widget.CardView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blockchain.securewallet.MainActivity;
import com.blockchain.securewallet.R;
import com.blockchain.securewallet.WalletApp;
import com.blockchain.securewallet.adapter.WordsAdapter;
import com.blockchain.securewallet.base.BaseActivity;
import com.blockchain.securewallet.dialog.CommonDialogFragment;
import com.blockchain.securewallet.dialog.DialogFragmentHelper;
import com.blockchain.securewallet.dialog.IDialogTipsListener;
import com.blockchain.securewallet.dialog.UniversalDialog;
import com.blockchain.securewallet.model.db.Account;
import com.blockchain.securewallet.model.db.CoinWallet;
import com.blockchain.securewallet.model.db.oper.AccountDaoOpe;
import com.blockchain.securewallet.tools.TipsWatcher;
import com.blockchain.securewallet.utils.Logger;
import com.blockchain.securewallet.utils.ToastUtils;

import org.bitcoinj.crypto.MnemonicCode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SeedWordsInputActivity extends BaseActivity implements WordsAdapter.IWordChangeWatch {

    public static final String KEY_WORDS_LIST = "key_words_list";

    @BindView(R.id.tv_title)
    TextView tvTitle;

    @BindView(R.id.rv_seed_edit)
    RecyclerView rvSeedEdit;

    //幕布
    @BindView(R.id.fl_curtain)
    FrameLayout flCurtain;

    private List<String> editSeeds = new ArrayList<>(12);

    private WordsAdapter adapterEdit = null;

    private String strCode = null;
    private String password = "";

    private PowerManager.WakeLock m_wklk;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_seed_words_input);
        // 设置Android软键盘的默认不弹出，不过这句不需要了，because 
        // 下面使用了clearFocus + view的parent的组合(android:focusableInTouchMode="true")
        // getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

        ButterKnife.bind(this);
        tvTitle.setText(R.string.input_seed);

        for (int i = 0; i < 12; i++) {
            editSeeds.add("");
        }

        Intent intent = getIntent();
        if (intent != null) {
            String words = intent.getStringExtra(KEY_WORDS_LIST);
            if (!TextUtils.isEmpty(words)) {
                //正则表达式"\\s+"表示至少会出现1个空格
                String[] ws = words.trim().split("\\s+");
                if (ws.length == 12) {
                    editSeeds = Arrays.asList(words.trim().split("\\s+"));
                } else {
                    ToastUtils.showToast("二维码信息不完整");
                }
            } else {
                //Logger.ds("" + words);
                if (words == null) {
                    //从种子密码恢复过来会错误地提示这个，暂时根据空判断做处理
                } else {
                    ToastUtils.showToast("二维码信息有误");
                }
            }
        }

        adapterEdit = new WordsAdapter(this, editSeeds);
        adapterEdit.setType(2);
        adapterEdit.setWatcher(this);

        rvSeedEdit.setLayoutManager(new GridLayoutManager(this, 3));
        //rvSeedEdit.addItemDecoration(new SpaceItemDecoration(UIHelper.dipToPx(1.0f)));
        rvSeedEdit.setAdapter(adapterEdit);
    }


    @Override
    protected void onResume() {
        super.onResume();

        //不发生点击事件之前才算有效
        if (rvSeedEdit != null) {

            Logger.ds("rvSeedEdit不为空");
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    CardView cv = (CardView) rvSeedEdit.getChildAt(0);

                    if (cv == null) {
                        Logger.ds("CardView为空");
                        return;
                    }

                    EditText editText = (EditText) cv.getChildAt(0);
                    if (TextUtils.isEmpty(editText.getText().toString())) {
                        editText.requestFocus();
                        Logger.ds("设置默认焦点");
                    } else {
                        Logger.ds("第一个输入框不为空");
                        editText.clearFocus();

                    }
                }
            }, 300);
        }
    }

    @OnClick(R.id.btn_back)
    void back() {
        finish();
    }

    @OnClick(R.id.btn_next)
    void next() {

        try {
            if (editSeeds.get(0).charAt(0) < 97) {
                WalletApp.getInstance().initMnemonicCode(WalletApp.BIP39_WORDLIST_NUMBER);
            } else {
                WalletApp.getInstance().initMnemonicCode(WalletApp.BIP39_WORDLIST_ENGLISH);
            }
            byte[] mnemonicSeedBytes = MnemonicCode.INSTANCE.toEntropy(editSeeds);

        } catch (Exception e) {
            e.printStackTrace();
            Log.i("cuowei", "              " + e.toString());
            Toast.makeText(this, "种子密码不正确", Toast.LENGTH_SHORT).show();
            //Toast.makeText(this, "种子密码错误！！！" + e.getMessage(), Toast.LENGTH_SHORT).show();
            return;
        }

        UniversalDialog dialog = UniversalDialog.showDialog(getSupportFragmentManager(), new IDialogTipsListener() {
            @Override
            public void onItemClick(View view, String... texts) {
                if (texts.length != 2) {
                    return;
                }

                final TextView tv_err = view.findViewById(R.id.tv_tips_pw_err);
                EditText edit_first_pw = view.findViewById(R.id.edit_first_password);
                EditText edit_second_pw = view.findViewById(R.id.edit_second_password);

                /*TextView tv_tips_friendly = view.findViewById(R.id.tv_tips_friendly);
                TextView tv_tips_content = view.findViewById(R.id.tv_tips_content);
                tv_tips_friendly.setVisibility(View.VISIBLE);
                tv_tips_content.setVisibility(View.VISIBLE);*/

                TipsWatcher watcher = new TipsWatcher(tv_err, true);
                edit_first_pw.addTextChangedListener(watcher);
                edit_second_pw.addTextChangedListener(watcher);

                if (TextUtils.isEmpty(texts[0]) || TextUtils.isEmpty(texts[1])) {
                    tv_err.setText("*密码不能为空");
                    tv_err.setVisibility(View.VISIBLE);

                } else if (texts[0].length() < 5 || texts[1].length() < 5) {
                    tv_err.setText("*密码长度不能小于5位");
                    tv_err.setVisibility(View.VISIBLE);

                } else if (!texts[0].equals(texts[1])) {
                    tv_err.setText("*两次密码输入不一致");
                    tv_err.setVisibility(View.VISIBLE);

                } else {
                    password = texts[0];
                    StringBuilder builder = new StringBuilder();
                    for (String item : editSeeds) {
                        builder.append(item).append(" ");
                    }
                    strCode = builder.toString().trim();
                    generateWalletAsync();
                }
                //Toast.makeText(SeedVerifyActivity.this,"ok-->"+text1.equals(text2),Toast.LENGTH_SHORT).show();
            }
        });
    }


    @Override
    public void dataChanged(int pos, String text) {
        editSeeds.set(pos, text);
        //从种子验证界面复制而来，可自动移动焦点
        //EditText 每次修改都更改助记词列表
        //editSeeds.set(pos, text);

//        if (rvSeedEdit != null && isTextChange && pos < 11) {
//            new Handler().postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    /*//获得第一项
//                    CardView $cv = (CardView) rvSeedEdit.getChildAt(0);
//                    EditText $et = (EditText) $cv.getChildAt(0);
//                    if (TextUtils.isEmpty($et.getText().toString())) {
//                        $et.requestFocus();
//                        return;
//                    }*/
//
//                    CardView cv = (CardView) rvSeedEdit.getChildAt(pos + 1);
//                    EditText et = (EditText) cv.getChildAt(0);
//
//                    et.requestFocus();
//                    isTextChange = false;
//                    //Logger.ds("当前: " + pos + "\t下一个获取焦点");
//                }
//            }, 300);
//
//        }

        // Logger.ds(">上面的编辑框的第" + pos + "个改变了: " + text);
    }


    private void generateWalletAsync() {
        new AsyncTask<Void, Void, Void>() {
            CommonDialogFragment loadDialog;

            @Override
            protected void onPreExecute() {
                flCurtain.setVisibility(View.VISIBLE);
                loadDialog = DialogFragmentHelper.showProgress(getSupportFragmentManager(), getString(R.string.wallet_loading_restore), false);
            }

            @Override
            protected Void doInBackground(Void... voids) {
//                WalletApp.getInstance().getDaoSession().getUnSpentDao().deleteAll();

                PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
                m_wklk = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "cn");
                m_wklk.acquire(); //设置保持唤醒

                List<CoinWallet> coinWallets = new ArrayList<>();
                coinWallets.addAll(CoinWallet.createAllWallet(strCode, password));
                Account account = new Account();
                account.setAccountId(WalletApp.uuid);
                account.setPayPassword(password);
                account.setTime(System.currentTimeMillis());
                account.setMemorizing_words(strCode);
                account.setCoinWalletList(coinWallets);
                AccountDaoOpe.insertData(SeedWordsInputActivity.this, account);
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                try {
                    if (loadDialog != null) {
                        loadDialog.dismiss();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("errors", "onPostExecute:restore dialog dismiss err: " + e.getMessage(), e.fillInStackTrace());
                } finally {
                    MainActivity.startFromWalletCreate(SeedWordsInputActivity.this);
                    m_wklk.release(); //解除保持唤醒
                    finish();
                }



            }
        }.execute();
    }


}
